package jp.co.nes.awssupport.sforce.function;

import java.time.YearMonth;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.amazonaws.services.batch.model.SubmitJobResult;

import jp.co.nes.awssupport.business.bean.CommonContainerBean;
import jp.co.nes.awssupport.business.bean.CommonContainerBean.ProcessingResult;
import jp.co.nes.awssupport.business.bean.CommonInfoBean;
import jp.co.nes.awssupport.business.logic.CompileProgressManage;
import jp.co.nes.awssupport.common.base.AbstractRequestHandler;
import jp.co.nes.awssupport.common.base.CommonException;
import jp.co.nes.awssupport.common.utility.AppInfoUtil;
import jp.co.nes.awssupport.common.utility.AwsBatchAsyncHelper;
import jp.co.nes.awssupport.common.utility.BeanUtil;
import jp.co.nes.awssupport.common.utility.DateUtil;

/**
 * Sforce反映起動です(Lambda)。
 */
public class SforceUpdateStart extends AbstractRequestHandler<CommonInfoBean, CommonContainerBean<CommonInfoBean>> {

    /** ロガー */
    private static Logger logger = LoggerFactory.getLogger(SforceUpdateStart.class);

    /**
     * デフォルトコンストラクタです。
     */
    public SforceUpdateStart() {
    }

    /*
     * (非 Javadoc)
     * @see jp.co.nes.awssupport.common.base.AbstractRequestHandler#handleRequest(java.lang.Object)
     */
    @Override
    protected CommonContainerBean<CommonInfoBean> handleRequest(CommonInfoBean input) {
        String category = "SforceUpdateStart";
        int waitTime = 0;
        ProcessingResult processingResult = null;
        YearMonth targetYearMonth = DateUtil.toYearMonth(input.getTargetYearMonthValue());
        CompileProgressManage cpManage = new CompileProgressManage(targetYearMonth);
        if (cpManage.isOkSforceUpdate()) {
            String jobNamePrefix = AppInfoUtil.getValAndEmptyChk(category, "JobNamePrefix");
            String jobQueue = AppInfoUtil.getValAndEmptyChk(category, "JobQueue");
            String jobDefinition = AppInfoUtil.getValAndEmptyChk(category, "JobDefinition");

            if (logger.isDebugEnabled()) {
                logger.debug(category + ",JobNamePrefix=" + jobNamePrefix);
                logger.debug(category + ",JobQueue=" + jobQueue);
                logger.debug(category + ",JobDefinition=" + jobDefinition);
            }

            // Sforce反映を起動
            AwsBatchAsyncHelper helper = null;
            try {
                helper = createAwsBatchAsyncHelper();
                Future<SubmitJobResult> future = helper.submitJobAsync(jobNamePrefix, jobQueue, jobDefinition);
                SubmitJobResult submitJobResult = future.get();

                StringBuilder builder = new StringBuilder();
                builder.append("JobId=");
                builder.append(submitJobResult.getJobId());
                builder.append(",JobName=");
                builder.append(submitJobResult.getJobName());
                logger.info(builder.toString());
            } catch (InterruptedException | ExecutionException e) {
                throw new CommonException(e);
            } finally {
                if (helper != null) {
                    helper.shutdown();
                }
            }

            waitTime = 0;
            processingResult = ProcessingResult.SUCCESS;
        } else {
            waitTime = AppInfoUtil.getIntValAndEmptyMinChk(category, "WaitTime", 0);

            if (logger.isDebugEnabled()) {
                logger.debug(category + ",WaitTime=" + waitTime);
            }

            processingResult = ProcessingResult.WAIT;
        }

        // 返却内容の設定
        CommonInfoBean info = new CommonInfoBean();
        BeanUtil.copyProperties(info, input);
        info.setWaitTime(waitTime);
        CommonContainerBean<CommonInfoBean> output = new CommonContainerBean<>();
        output.setInfoBean(info);
        output.setProcessingResult(processingResult);
        return output;
    }

    /**
     * AwsBatchAsyncヘルパーを生成します。
     *
     * @return AwsBatchAsyncヘルパー
     */
    protected AwsBatchAsyncHelper createAwsBatchAsyncHelper() {
        return new AwsBatchAsyncHelper();
    }
}
